package config

import (
	"fmt"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"

	"gopkg.in/go-module/log.v1"
	"gopkg.in/ini.v1"
)

const (
	APP_VER  = "1.0.6.0528"
	CFG_PATH = "conf/app.ini"
)

type Configuration struct {
	MaxFileSize int64
	HashLength  int
	UserAgent   string
	Stores      []map[string]string
}

var (
	AppName, AppVer                string
	HttpAddr, HttpPort             string
	ConfPath                       string
	AWS_AccessKeyID, AWS_SecretKey string
	LocalStore                     string

	// Global setting objects.
	Cfg *ini.File
)

func NewConfiguration() *Configuration {
	workDir, err := WorkDir()
	if err != nil {
		log.Fatal(4, "Fail to get work directory: %v", err)
	}
	//fmt.Println(workDir)
	ConfPath = CFG_PATH
	//pwd, _ := os.Getwd()

	//判断INI文件是否存在
	if !IsFile(path.Join(workDir, ConfPath)) {
		log.Warn("System config (%s) not found, ignore this if you're running first time", ConfPath)
	}

	Cfg, err = ini.Load(ConfPath)
	if err != nil {
		log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
	}
	cfg := new(Configuration)
	httpd := Cfg.Section("httpd")
	AppName = httpd.Key("app_name").MustString("ImgurGo Service by Aukeys Inc.")
	AppVer = APP_VER
	HttpAddr = httpd.Key("http_addr").MustString("0.0.0.0")
	HttpPort = httpd.Key("http_port").MustString("9900")
	cfg.MaxFileSize = httpd.Key("max_file_size").MustInt64(20971520)
	cfg.HashLength = httpd.Key("hash_length").MustInt(7)
	cfg.UserAgent = httpd.Key("user_agent").MustString("ImgurGo (https://git.oschina.net/kevinGunn/Imgur)")

	stores := make([]map[string]string, 0)
	store_local := Cfg.Section("stores.local")
	local := make(map[string]string)
	local["Type"] = store_local.Key("type").MustString("local")
	local["ViweDomian"] = store_local.Key("viwe_domian").MustString(fmt.Sprintf("http://%s:%s/", HttpAddr, HttpPort))
	local["StoreRoot"] = store_local.Key("store_root").MustString("imagestores")
	LocalStore = local["StoreRoot"]
	local["NamePathRegex"] = store_local.Key("name_path_regex").MustString("")
	local["NamePathMap"] = store_local.Key("name_path_map").MustString("${ImageSize}/${ImageName}")
	stores = append(stores, local)

	//	store_s3 := Cfg.Section("stores.s3")
	//	s3 := make(map[string]string)
	//	s3["Type"] = store_s3.Key("type").MustString("s3")
	//	s3["ViweDomian"] = store_s3.Key("viwe_domian").MustString("")
	//	s3["BucketName"] = store_s3.Key("bucket_name").MustString("")
	//	s3["StoreRoot"] = store_s3.Key("store_root").MustString("")
	//	s3["Region"] = store_s3.Key("region").MustString("")
	//	s3["NamePathRegex"] = store_s3.Key("name_path_regex").MustString("")
	//	s3["NamePathMap"] = store_s3.Key("name_path_map").MustString("${ImageSize}/${ImageName}")
	//	AWS_AccessKeyID = store_s3.Key("AWS_ACCESS_KEY_ID").MustString("")
	//	AWS_SecretKey = store_s3.Key("AWS_SECRET_KEY").MustString("")
	//	os.Setenv("AWS_ACCESS_KEY_ID", AWS_AccessKeyID)
	//	os.Setenv("AWS_SECRET_KEY", AWS_SecretKey)
	//	stores = append(stores, s3)
	cfg.Stores = stores
	return cfg

}

func IsFile(filePath string) bool {
	f, e := os.Stat(filePath)
	if e != nil {
		return false
	}
	return !f.IsDir()
}

// WorkDir returns absolute path of work directory.
func WorkDir() (string, error) {
	execPath, err := ExecPath()
	return path.Dir(strings.Replace(execPath, "\\", "/", -1)), err
}

func ExecPath() (string, error) {
	file, err := exec.LookPath(os.Args[0])
	if err != nil {
		return "", err
	}
	p, err := filepath.Abs(file)
	if err != nil {
		return "", err
	}
	return p, nil
}
